import fs from 'fs'
import path, { dirname } from 'path'
import { fileURLToPath } from 'url'
import { spawn, execSync } from 'child_process'
import { PDFDocument, rgb } from 'pdf-lib'
import fontkit from '@pdf-lib/fontkit'
import sharp from 'sharp'
import libre from 'libreoffice-convert'
import { promisify } from 'util'
import mammoth from 'mammoth'
import htmlPdf from 'html-pdf-node'
import * as XLSX from 'xlsx'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const convertAsync = promisify(libre.convert)

// 使用mammoth.js转换DOCX为PDF（纯JavaScript方案）
const convertDocxToPdfWithMammoth = async (inputPath, outputDir) => {
  try {
    const baseName = path.basename(inputPath, path.extname(inputPath))
    const outputPath = path.join(outputDir, `${baseName}.pdf`)
    
    // 确保输出目录存在
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true })
    }
    
    // 使用mammoth将DOCX转换为HTML
    const result = await mammoth.convertToHtml({ path: inputPath })
    const html = result.value
    
    const css = `${getEmbeddedFontCss()}body{font-family:SimSunEmbedded,\"Arial Unicode MS\",\"Noto Sans CJK SC\",\"Microsoft YaHei\",sans-serif;line-height:1.6;margin:40px;color:#333}p{margin-bottom:12px}h1,h2,h3,h4,h5,h6{margin-top:20px;margin-bottom:10px;color:#2c3e50}table{border-collapse:collapse;width:100%;margin:20px 0}th,td{border:1px solid #ddd;padding:8px;text-align:left}th{background-color:#f2f2f2}`
    const styledHtml = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <style>${css}</style>
      </head>
      <body>
        ${html}
      </body>
      </html>
    `
    
    // 使用html-pdf-node将HTML转换为PDF
    const options = {
      format: 'A4',
      margin: {
        top: '20mm',
        bottom: '20mm',
        left: '20mm',
        right: '20mm'
      }
    }
    
    const file = { content: styledHtml }
    const pdfBuffer = await htmlPdf.generatePdf(file, options)
    
    // 写入PDF文件
    fs.writeFileSync(outputPath, pdfBuffer)
    
    return outputPath
  } catch (error) {
    throw new Error(`Mammoth转换失败: ${error.message}`)
  }
}

// 检查LibreOffice是否可用
const checkLibreOfficeAvailable = () => {
  return new Promise((resolve) => {
    // 设置超时，避免长时间等待
    const timeout = setTimeout(() => {
      resolve(false)
    }, 5000)
    
    const child = spawn('soffice', ['--version'], { 
      stdio: 'ignore',
      windowsHide: true // Windows下隐藏窗口
    })
    
    child.on('close', (code) => {
      clearTimeout(timeout)
      resolve(code === 0)
    })
    
    child.on('error', () => {
      clearTimeout(timeout)
      resolve(false)
    })
  })
}

// 使用libreoffice-convert库转换Office文档为PDF
const convertOfficeToPdfWithLibre = async (inputPath, outputDir) => {
  let tempDirPath = null
  
  try {
    // 读取输入文件
    const inputBuffer = fs.readFileSync(inputPath)
    
    // 转换为PDF，添加超时和错误处理
    const pdfBuffer = await Promise.race([
      convertAsync(inputBuffer, '.pdf', undefined),
      new Promise((_, reject) => 
        setTimeout(() => reject(new Error('转换超时')), 30000)
      )
    ])
    
    // 生成输出文件路径
    const baseName = path.basename(inputPath, path.extname(inputPath))
    const outputPath = path.join(outputDir, `${baseName}.pdf`)
    
    // 确保输出目录存在
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true })
    }
    
    // 写入PDF文件
    fs.writeFileSync(outputPath, pdfBuffer)
    
    return outputPath
  } catch (error) {
    throw new Error(`libreoffice-convert转换失败: ${error.message}`)
  } finally {
    // 在finally块中强制清理所有可能的临时文件
    try {
      const tempDir = process.env.TMPDIR || process.env.TMP || process.env.TEMP || 'C:\\Windows\\Temp'
      
      // 查找所有libreoffice相关的临时目录
      const tempDirs = fs.readdirSync(tempDir).filter(dir => 
        dir.includes('libreofficeConvert_') || dir.includes('soffice')
      )
      
      for (const dir of tempDirs) {
        const fullPath = path.join(tempDir, dir)
        try {
          if (fs.existsSync(fullPath)) {
            const stats = fs.statSync(fullPath)
            // 只清理超过5分钟的临时目录，避免清理正在使用的
            if (Date.now() - stats.mtime.getTime() > 5 * 60 * 1000) {
              // 先尝试删除目录内的所有文件
              const files = fs.readdirSync(fullPath)
              for (const file of files) {
                const filePath = path.join(fullPath, file)
                try {
                  if (fs.statSync(filePath).isDirectory()) {
                    fs.rmSync(filePath, { recursive: true, force: true })
                  } else {
                    fs.unlinkSync(filePath)
                  }
                } catch (fileError) {
                  // 忽略单个文件删除失败
                }
              }
              // 然后删除空目录
              fs.rmdirSync(fullPath)
            }
          }
        } catch (cleanupError) {
          // 忽略清理失败，不影响主流程
          console.warn(`清理临时目录 ${fullPath} 失败:`, cleanupError.message)
        }
      }
    } catch (globalCleanupError) {
      console.warn('全局临时文件清理失败:', globalCleanupError.message)
    }
  }
}

// 使用LibreOffice转换Office文档为PDF (原方法保留作为备用)
const convertOfficeToPdf = (inputPath, outputDir) => {
  return new Promise((resolve, reject) => {
    // 确保输出目录存在
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true })
    }
    
    const args = [
      '--headless',
      '--convert-to', 'pdf',
      '--outdir', outputDir,
      inputPath
    ]
    
    console.log(`执行LibreOffice转换: soffice ${args.join(' ')}`)
    
    const child = spawn('soffice', args, {
      stdio: 'pipe',
      windowsHide: true // Windows下隐藏窗口
    })
    
    let stdout = ''
    let stderr = ''
    
    child.stdout?.on('data', (data) => {
      stdout += data.toString()
    })
    
    child.stderr?.on('data', (data) => {
      stderr += data.toString()
    })
    
    // 设置超时，避免长时间等待
    const timeout = setTimeout(() => {
      child.kill('SIGTERM')
      reject(new Error('LibreOffice转换超时（30秒）'))
    }, 30000)
    
    child.on('close', (code) => {
      clearTimeout(timeout)
      
      if (code === 0) {
        const baseName = path.basename(inputPath, path.extname(inputPath))
        const outputPath = path.join(outputDir, `${baseName}.pdf`)
        
        // 检查输出文件是否存在
        if (fs.existsSync(outputPath)) {
          console.log(`LibreOffice转换成功: ${outputPath}`)
          resolve(outputPath)
        } else {
          reject(new Error(`LibreOffice转换失败：输出文件不存在 ${outputPath}`))
        }
      } else {
        const errorMsg = stderr || stdout || `LibreOffice转换失败，退出码: ${code}`
        console.error('LibreOffice转换错误:', errorMsg)
        reject(new Error(errorMsg))
      }
    })
    
    child.on('error', (error) => {
      clearTimeout(timeout)
      console.error('LibreOffice执行错误:', error.message)
      reject(new Error(`LibreOffice执行失败: ${error.message}`))
    })
  })
}

// 将图片转换为PDF
const convertImageToPdf = async (imagePath, outputPath) => {
  try {
    // 使用sharp处理图片
    const imageBuffer = await sharp(imagePath)
      .jpeg({ quality: 80 })
      .toBuffer()
    
    // 创建PDF文档
    const pdfDoc = await PDFDocument.create()
    
    // 将图片嵌入PDF
    const jpgImage = await pdfDoc.embedJpg(imageBuffer)
    const { width, height } = jpgImage.scale(1)
    
    // 创建页面
    const page = pdfDoc.addPage([width, height])
    page.drawImage(jpgImage, {
      x: 0,
      y: 0,
      width,
      height
    })
    
    // 保存PDF
    const pdfBytes = await pdfDoc.save()
    fs.writeFileSync(outputPath, pdfBytes)
    
    return outputPath
  } catch (error) {
    throw new Error(`图片转PDF失败: ${error.message}`)
  }
}

// 创建一个函数来过滤或替换不支持的字符
const sanitizeTextForPdf = (text) => {
  if (text === null || text === undefined) return ''
  return String(text)
}

const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')

const getEmbeddedFontCss = () => {
  try {
    const fontPath = path.join(process.cwd(), 'simsun.ttf')
    const fontBytes = fs.readFileSync(fontPath)
    const base64 = fontBytes.toString('base64')
    return `@font-face{font-family:"SimSunEmbedded";src:url(data:font/ttf;base64,${base64}) format('truetype');font-weight:normal;font-style:normal;}`
  } catch {
    return ''
  }
}

const convertTextToPdfHtml = async (textPath, outputPath) => {
  const textContent = fs.readFileSync(textPath, 'utf-8')
  const css = `${getEmbeddedFontCss()}body{font-family:SimSunEmbedded,\"Arial Unicode MS\",\"Noto Sans CJK SC\",\"Microsoft YaHei\",sans-serif;line-height:1.6;margin:24px;color:#333;white-space:pre-wrap;word-break:break-word;}pre{white-space:pre-wrap;word-wrap:break-word;}`
  const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>${css}</style></head><body><pre>${escapeHtml(textContent)}</pre></body></html>`
  const options = { format: 'A4', margin: { top: '16mm', bottom: '16mm', left: '16mm', right: '16mm' } }
  const file = { content: html }
  const pdfBuffer = await htmlPdf.generatePdf(file, options)
  fs.writeFileSync(outputPath, pdfBuffer)
  return outputPath
}

const convertExcelToPdfHtml = async (excelPath, outputPath) => {
  const fileBuffer = fs.readFileSync(excelPath)
  const workbook = XLSX.read(fileBuffer, { type: 'buffer' })
  const parts = []
  for (const name of workbook.SheetNames) {
    const sheet = workbook.Sheets[name]
    const tableHtml = XLSX.utils.sheet_to_html(sheet, { header: name })
    parts.push(tableHtml)
  }
  const css = `${getEmbeddedFontCss()}body{font-family:SimSunEmbedded,\"Arial Unicode MS\",\"Noto Sans CJK SC\",\"Microsoft YaHei\",sans-serif;margin:16px;color:#333}table{border-collapse:collapse;width:100%;font-size:12px}th,td{border:1px solid #ccc;padding:4px;text-align:left}h1{font-size:16px;margin:12px 0}`
  const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>${css}</style></head><body>${parts.join('<div style="page-break-after:always"></div>')}</body></html>`
  const options = { format: 'A4', margin: { top: '10mm', bottom: '10mm', left: '10mm', right: '10mm' } }
  const file = { content: html }
  const pdfBuffer = await htmlPdf.generatePdf(file, options)
  fs.writeFileSync(outputPath, pdfBuffer)
  return outputPath
}

// 将Excel文件转换为PDF
const convertExcelToPdf = async (excelPath, outputPath) => {
  console.log('开始转换Excel文件:', excelPath);

  try {
    // 读取Excel文件 - 使用read方法而不是readFile
    const fileBuffer = fs.readFileSync(excelPath);
    const workbook = XLSX.read(fileBuffer, { type: 'buffer' });

    const pdfDoc = await PDFDocument.create()
    pdfDoc.registerFontkit(fontkit)
    const fontPath = path.join(process.cwd(), 'simsun.ttf')
    const fontBytes = fs.readFileSync(fontPath)
    const customFont = await pdfDoc.embedFont(fontBytes)

    // 遍历所有工作表
    const sheetNames = workbook.SheetNames;
    console.log('工作表数量:', sheetNames.length);

    for (let i = 0; i < sheetNames.length; i++) {
      const sheetName = sheetNames[i];
      console.log('处理工作表:', sheetName);
      const worksheet = workbook.Sheets[sheetName];

      // 获取工作表的范围
      const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1:A1');
      console.log('工作表范围:', range);

      // 计算表格所需的最小宽度
      const maxCols = range.e.c + 1;
      const minColWidth = 60; // 最小列宽
      const requiredWidth = maxCols * minColWidth + 100; // 加上边距

      // 根据数据宽度决定页面方向和尺寸
      let pageWidth, pageHeight, isLandscape = false;
      
      if (requiredWidth > 595) { // A4纵向宽度
        // 尝试横向布局
        if (requiredWidth <= 842) { // A4横向宽度
          pageWidth = 842;
          pageHeight = 595;
          isLandscape = true;
          console.log('使用横向布局');
        } else {
          // 使用更大的页面尺寸或缩放
          pageWidth = Math.min(requiredWidth + 100, 1200); // 最大宽度限制
          pageHeight = 842;
          isLandscape = true;
          console.log('使用自定义大页面:', pageWidth, 'x', pageHeight);
        }
      } else {
        // 使用标准纵向布局
        pageWidth = 595;
        pageHeight = 842;
        console.log('使用纵向布局');
      }

      // 创建新页面
      let page = pdfDoc.addPage([pageWidth, pageHeight]);
      const { width, height } = page.getSize();

      // 设置字体和大小
      const fontSize = 8; // 稍微减小字体以容纳更多内容
      const lineHeight = fontSize * 1.4;
      const margin = 30; // 减小边距
      let yPosition = height - margin;

      // 添加工作表标题
      const sanitizedSheetName = sanitizeTextForPdf(sheetName)
      page.drawText(`Sheet: ${sanitizedSheetName}`, {
        x: margin,
        y: yPosition,
        font: customFont,
        size: fontSize + 2,
        color: rgb(0, 0, 0)
      });
      yPosition -= lineHeight * 2;

      // 重新计算列宽，确保所有列都能显示
      const availableWidth = width - 2 * margin;
      let colWidth = availableWidth / maxCols;
      
      // 如果计算出的列宽太小，使用缩放因子
      const minDisplayWidth = 40; // 最小可读列宽
      let scaleFactor = 1;
      
      if (colWidth < minDisplayWidth) {
        scaleFactor = minDisplayWidth / colWidth;
        colWidth = minDisplayWidth;
        console.log('应用缩放因子:', scaleFactor);
      }

      // 动态调整字体大小
      const adjustedFontSize = Math.max(6, fontSize / Math.sqrt(scaleFactor));
      const adjustedLineHeight = adjustedFontSize * 1.4;

      console.log('列数:', maxCols, '列宽:', colWidth, '字体大小:', adjustedFontSize);

      // 绘制表格
      for (let row = range.s.r; row <= range.e.r; row++) {
        // 检查是否需要新页面
        if (yPosition < margin + adjustedLineHeight * 2) {
          page = pdfDoc.addPage([pageWidth, pageHeight]);
          const { height: newHeight } = page.getSize();
          yPosition = newHeight - margin;
          
          // 重新绘制标题
          page.drawText(`Sheet: ${sanitizedSheetName} (续)`, {
            x: margin,
            y: yPosition,
            font: customFont,
            size: adjustedFontSize + 2,
            color: rgb(0, 0, 0)
          });
          yPosition -= adjustedLineHeight * 2;
        }

        let xPosition = margin;

        // 绘制行的边框线（上边框）
        page.drawLine({
          start: { x: margin, y: yPosition + adjustedLineHeight },
          end: { x: margin + maxCols * colWidth, y: yPosition + adjustedLineHeight },
          thickness: 0.3,
          color: rgb(0, 0, 0)
        });

        for (let col = range.s.c; col <= range.e.c; col++) {
          // 绘制列的边框线（左边框）
          page.drawLine({
            start: { x: xPosition, y: yPosition + adjustedLineHeight },
            end: { x: xPosition, y: yPosition },
            thickness: 0.3,
            color: rgb(0, 0, 0)
          });

          // 获取单元格值
          const cellAddress = XLSX.utils.encode_cell({ r: row, c: col });
          const cell = worksheet[cellAddress];
          let cellValue = '';
          
          if (cell) {
            if (cell.t === 'n') { // 数字
              cellValue = cell.v.toString();
            } else if (cell.t === 's') { // 字符串
              cellValue = sanitizeTextForPdf(cell.v)
            } else if (cell.t === 'b') { // 布尔值
              cellValue = cell.v ? 'TRUE' : 'FALSE';
            } else if (cell.t === 'd') { // 日期
              cellValue = cell.v.toDateString();
            } else {
              cellValue = cell.v ? cell.v.toString() : '';
            }
          }

          // 根据列宽智能截断文本
          const maxChars = Math.floor(colWidth / (adjustedFontSize * 0.6));
          if (cellValue.length > maxChars && maxChars > 3) {
            cellValue = cellValue.substring(0, maxChars - 3) + '...';
          }

          // 绘制单元格文本
          if (cellValue) {
            page.drawText(cellValue, {
              x: xPosition + 2, // 小的内边距
              y: yPosition + 2,
              font: customFont,
              size: adjustedFontSize,
              color: rgb(0, 0, 0)
            });
          }

          xPosition += colWidth;
        }

        // 绘制最右边的边框线
        page.drawLine({
          start: { x: margin + maxCols * colWidth, y: yPosition + adjustedLineHeight },
          end: { x: margin + maxCols * colWidth, y: yPosition },
          thickness: 0.3,
          color: rgb(0, 0, 0)
        });

        yPosition -= adjustedLineHeight;
      }

      // 绘制表格底部边框
      page.drawLine({
        start: { x: margin, y: yPosition + adjustedLineHeight },
        end: { x: margin + maxCols * colWidth, y: yPosition + adjustedLineHeight },
        thickness: 0.3,
        color: rgb(0, 0, 0)
      });
    }

  // 保存PDF
  console.log('保存PDF文件...');
  const pdfBytes = await pdfDoc.save()
  fs.writeFileSync(outputPath, pdfBytes)

  console.log(`Excel转PDF成功: ${outputPath}`);
  return outputPath;
  } catch (error) {
    console.error('Excel转PDF失败:', error);
    throw new Error(`Excel转PDF失败: ${error.message}`);
  }
}

const convertTextToPdf = async (textPath, outputPath) => {
  try {
    console.log('开始转换TXT文件:', textPath)
    const textContent = fs.readFileSync(textPath, 'utf-8')

    // 创建PDF文档
    const pdfDoc = await PDFDocument.create()
    pdfDoc.registerFontkit(fontkit)
    const fontPath = path.join(process.cwd(), 'simsun.ttf')
    const fontBytes = fs.readFileSync(fontPath)
    const customFont = await pdfDoc.embedFont(fontBytes)

    // 设置字体和大小
    const fontSize = 12
    const lineHeight = fontSize * 1.5  // 增加行间距，避免重叠
    const margin = 50
    const maxWidth = 500  // 设置最大文本宽度

    // 分割文本为行并处理长行
    const rawLines = textContent.split('\n')
    const processedLines = []
    
    for (const rawLine of rawLines) {
      if (rawLine.trim() === '') {
        // 保留空行
        processedLines.push('')
        continue
      }
      
      // 处理长行，按字符数分割
      const maxCharsPerLine = 80  // 每行最大字符数
      if (rawLine.length <= maxCharsPerLine) {
        processedLines.push(rawLine)
      } else {
        // 分割长行
        for (let i = 0; i < rawLine.length; i += maxCharsPerLine) {
          processedLines.push(rawLine.substring(i, i + maxCharsPerLine))
        }
      }
    }

    let currentPage = pdfDoc.addPage()
    let { width, height } = currentPage.getSize()
    let yPosition = height - margin

    console.log(`处理 ${processedLines.length} 行文本`)

    for (let i = 0; i < processedLines.length; i++) {
      const line = processedLines[i]
      
      // 检查是否需要新页面
      if (yPosition < margin + lineHeight) {
        console.log(`创建新页面，当前行: ${i + 1}`)
        currentPage = pdfDoc.addPage()
        const pageSize = currentPage.getSize()
        width = pageSize.width
        height = pageSize.height
        yPosition = height - margin
      }

      // 过滤和清理文本
      const sanitizedLine = sanitizeTextForPdf(line)
      
      // 绘制文本到当前页面
      currentPage.drawText(sanitizedLine, {
        x: margin,
        y: yPosition,
        font: customFont,
        size: fontSize,
        color: rgb(0, 0, 0),
        maxWidth: maxWidth,
        lineHeight: lineHeight
      })

      // 更新Y位置
      yPosition -= lineHeight
    }

    console.log('保存PDF文件:', outputPath)
    // 保存PDF
    const pdfBytes = await pdfDoc.save()
    fs.writeFileSync(outputPath, pdfBytes)

    console.log('TXT转PDF转换完成')
    return outputPath
  } catch (error) {
    console.error('TXT转PDF转换失败:', error)
    throw error
  }
}

// 主转换函数
export const convertFileToPdf = async (inputPath, outputDir, mimetype) => {
  const baseName = path.basename(inputPath, path.extname(inputPath))
  const outputPath = path.join(outputDir, `${baseName}.pdf`)
  
  try {
    switch (mimetype) {
      case 'application/pdf':
        // 已经是PDF，直接返回原路径
        return inputPath
        
      case 'application/msword':
      case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': {
        let wordError = null
        const fileExt = path.extname(inputPath).toLowerCase()
        
        if (fileExt === '.docx') {
          try {
            console.log('使用Mammoth.js转换DOCX文档')
            return await convertDocxToPdfWithMammoth(inputPath, outputDir)
          } catch (error) {
            console.log(`Mammoth.js转换失败: ${error.message}`)
            wordError = error
          }
        }
        
        const libreOfficeAvailable = await checkLibreOfficeAvailable()
        if (libreOfficeAvailable) {
          try {
            console.log('使用系统LibreOffice转换Word文档')
            return await convertOfficeToPdf(inputPath, outputDir)
          } catch (sysError) {
            console.log('系统LibreOffice转换失败:', sysError.message)
            wordError = sysError
          }
        } else {
          console.log('系统未安装LibreOffice或不可用，跳过LibreOffice转换')
        }
        
        throw new Error(`Word文档转换失败：本机未安装LibreOffice或转换失败；对于DOCX已尝试纯JavaScript方案但仍失败。请安装LibreOffice或将文档另存为DOCX重新上传。最后错误: ${wordError?.message || '未知错误'}`)
      }
        
      case 'application/vnd.ms-excel':
      case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': {
        // 优先使用纯JavaScript绘制，资源占用更可控
        try {
          return await convertExcelToPdf(inputPath, outputPath)
        } catch (xlsxError) {
          console.error('XLSX绘制转换失败:', xlsxError)
        }

        // 回退到HTML渲染
        try {
          return await convertExcelToPdfHtml(inputPath, outputPath)
        } catch (htmlError) {
          console.error('XLSX回退HTML转换失败:', htmlError)
        }

        // 最后尝试LibreOffice转换（在资源紧张时可能不稳定）
        const libreOfficeAvailable = await checkLibreOfficeAvailable()
        if (libreOfficeAvailable) {
          try {
            return await convertOfficeToPdfWithLibre(inputPath, outputDir)
          } catch (libreError) {
            console.error('LibreOffice转换Excel失败:', libreError)
          }
        }
        throw new Error('Excel转换失败：JS绘制/HTML/LibreOffice均未成功')
      }

      case 'image/jpeg':
      case 'image/png':
      case 'image/gif':
        // 图片转换
        return await convertImageToPdf(inputPath, outputPath)
        
      case 'text/plain':
      case 'text/rtf':
      case 'application/rtf':
        try {
          return await convertTextToPdf(inputPath, outputPath)
        } catch (textError) {
          console.error('TXT转PDF失败，回退到HTML方式:', textError)
          return await convertTextToPdfHtml(inputPath, outputPath)
        }
        
      default:
        throw new Error(`不支持的文件类型: ${mimetype}`)
    }
  } catch (error) {
    throw new Error(`文件转换失败: ${error.message}`)
  }
}

// 验证转换后的PDF文件
export const validatePdfFile = async (pdfPath) => {
  try {
    const pdfBytes = fs.readFileSync(pdfPath)
    const pdfDoc = await PDFDocument.load(pdfBytes)
    const pageCount = pdfDoc.getPageCount()
    
    return {
      isValid: true,
      pageCount,
      fileSize: pdfBytes.length
    }
  } catch (error) {
    return {
      isValid: false,
      error: error.message
    }
  }
}
